<template>
  <div>
    <!-- 添加一行按钮 -->
    <div style="text-align: right;">
      <a-button type="primary" @click="onAddRow" style="margin-bottom: 16px">
        + {{ $t('all.autotext409') }}
      </a-button>
    </div>
    <a-table
      :columns="columns"
      row-key="id"
      :data-source="data"
      bordered
    >
      <template slot="name" slot-scope="text, record, index">
        <!-- 只有 name 列是下拉框 -->
        <a-input :disabled="['1','2','3'].includes(record.type)" v-if="record.editable" :value="text"
                 @change="e => handleChange(e.target.value, index, 'name')" style="margin: -5px 0; width: 100%"
        />
        <span v-else>
          {{ text }}
        </span>
      </template>
      <template slot="urlName" slot-scope="text, record, index">
        <!-- 只有 urlName 列在编辑模式下是文件上传组件 -->
        <a-upload v-if="record.editable" :custom-request="customRequest"
                  :file-list="record.fileList" style="margin: -5px 0; width: 100%"
                  :remove="file => handleFileRemove(index)" @change="info => handleFileChange(info, index)"
                  :before-upload="beforeUpload"
        >
          <a-button>{{ $t('all.autotext1324') }}</a-button>
        </a-upload>
        <!-- 非编辑模式下显示文本 -->
        <span v-if="!record.editable">
          <a
            v-if="record.url"
            :href="`https://minio-cluster.primelifescience.com.cn${record.url}`"
          >
            {{ text }}
          </a>
          <span v-else>
            {{ text }}
          </span>
        </span>
      </template>
      <template slot="payload" slot-scope="text, record, index">
        <!-- 只有 payload 列是可编辑的 -->
        <a-input v-if="record.editable" type="number" style="margin: -5px 0; width: 100%"
                 :min="5" :max="60" :value="text" @input="e => handleChange(e.target.value, index, 'payload')"
        />
        <span v-else>
          {{ text }}
        </span>
      </template>
      <template slot="operation" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a @click="() => save(record)">{{ $t('all.autotext321') }}</a>
            <a @click="() => cancel(record, index)">{{ $t('all.autotext975') }}</a> <!-- 新增取消按钮 -->
          </span>
          <span v-else>
            <a :disabled="editingKey !== ''" @click="() => edit(record)">{{ $t('all.autotext919') }}</a>
            <a-popconfirm title="确定删除此行?" @confirm="() => deleteRow(record)" v-if="record.type === '4'">
              <a>{{ $t('all.autotext379') }}</a>
            </a-popconfirm>
          </span>
        </div>
      </template>
    </a-table>
  </div>
</template>

<script>
import { uploadFile } from '@/api/organization/organization'
import { getList, addRow, deletRow, editRow } from '@/api/overview/agreement'

export default {
  data () {
    return {
      columns: [
        {
          title: this.$t('all.autotext334'),
          dataIndex: 'index',
          key: 'index',
          customRender: (text, record, index) => index + 1 // 序号列，自动编号
        },
        {
          title: this.$t('all.autotext91'),
          dataIndex: 'name',
          width: '25%',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '文件名',
          dataIndex: 'urlName',
          width: '40%',
          scopedSlots: { customRender: 'urlName' }
        },
        {
          title: '最少查看时间/S',
          dataIndex: 'payload',
          width: '15%',
          scopedSlots: { customRender: 'payload' }
        },
        {
          title: this.$t('all.autotext187'),
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      data: [],
      editingKey: '',
      count: 1, // 用来生成新 key
      configId: '',
      proId: this.$store.getters.project.id
    }
  },
  created () {
    this.configId = this.$route.query.configId
  },
  mounted () {
    this.getAgreementList()
  },
  methods: {
    handleFileRemove (index) {
      const newData = [...this.data]
      this.data.splice(index, 1, { ...newData[index], fileList: [],url: '',urlName: '' })
    },
    beforeUpload (file) {
      const isPdf = file.type === 'application/pdf'
      if (!isPdf) {
        this.$message.error('只能上传 PDF 文件!')
      }
      return isPdf // 返回 true 允许上传，false 阻止上传
    },
    async getAgreementList () {
      try {
        const response = await getList({ proId: this.proId, configId: this.configId })
        this.data = response
      } catch (err) {
        console.log('err', err)
      }
    },
    // 处理输入框的值变化
    handleChange (value, index, column) {
      const newData = [...this.data]
      this.data.splice(index, 1, { ...newData[index], [column]: value })
    },
    // 处理文件上传变化
    async handleFileChange (info, index) {
      const file = info.file.originFileObj
      if (file) {
        try {
          const formData = new FormData()
          formData.append('file', file)
          const response = await uploadFile(formData)
          const newData = [...this.data]
          // const target = newData.find(item => id === item.id)
          this.data.splice(index, 1, {
            ...newData[index],
            url: response,
            urlName: file.name,
            fileList: [{ name: file.name, uid: file.uid }]
          })
        } catch (error) {
          console.error('文件上传失败:', error)
        }
      }
    },
    // 编辑行
    edit (record) {
      const { id } = record
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        this.editingKey = id
        target.editable = true
        target.fileList = record.urlName ? [{ name: record.urlName, uid: id }] : []
        this.data = newData
      }
    },
    // 保存行
    async save (record) {
      try {
        delete record.modifyTime
        delete record.createTime
        delete record.fileList
        const requestAddr = record.id ? editRow : addRow
        await requestAddr({ ...record, proId: this.proId, configId: this.configId, docType: 3 })
        delete record.editable
        this.getAgreementList()
        this.editingKey = ''
      } catch (err) {
        console.log('err', err)
      }
    },
    // 删除行
    async deleteRow (record) {
      if (record.id) {
        try {
          await deletRow({ id: record.id })
          this.getAgreementList()
        } catch (err) {
          console.error('删除失败:', err)
        }
      }
    },
    // 新增一行，并设为可编辑状态
    onAddRow () {
      const newKey = this.count.toString()
      const newRow = {
        key: newKey,
        url: '',
        editable: true,
        name: '其他'
      }
      this.data.push(newRow)
      this.count += 1 // 更新 key 计数器
    },
    cancel (record, index) {
      console.log('index', index)
      if (!record.id) {
        // 如果没有 id，说明是新添加的行，直接删除
        // const newData = this.data.filter(item => item.id !== record.id)
        // this.data = newData
        this.data.splice(index, 1)
      } else {
        // 如果有 id，取消编辑模式并保留该行
        const newData = [...this.data]
        const target = newData.find(item => record.id === item.id)
        if (target) {
          delete target.editable
          this.data = newData
        }
      }
      this.editingKey = ''
    },
    // 处理文件上传请求
    customRequest ({ file, onSuccess, onError }) {
      const formData = new FormData()
      formData.append('file', file)
      uploadFile(formData)
        .then((response) => {
          onSuccess(response, file) // 修改为传递正确的响应
        })
        .catch((error) => {
          onError(error)
        })
    }
  }
}
</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
